# 登录界面
def login():
    print("欢迎使用学生信息管理系统")
    while True:
        role = input("请输入登录角色(1-学生,2-管理员）：")
        if role == '1':
            student_accounts()
            break
        elif role == '2':
            login_admin()
            break
        else:
            print("输入有误，请重新输入")
 
 
# 学生登录
def student_accounts():
    while True:
        account = input("请输入账号：")
        passwd = input("请输入密码：")
        with open('student_accounts.txt', 'r', encoding='utf-8') as f:
            for line in f:
                data = line.strip().split()
                name = data[0].split(':')[1].strip()
                num = data[1].split(':')[1].strip()
                acc = data[2].split(':')[1].strip()
                pwd = data[3].split(':')[1].strip()
                if (acc == account) and (pwd == passwd):
                    print(f"欢迎登陆，{name}同学！")
                    student_menu(account)
                    return
            print("账号或密码错误，请重新输入")
 
# 学生菜单
def student_menu(account):
    while True:
        print("""
        ============================================
            - 1. 查询个人信息
            - 2. 退回登录界面
            - 0. 退出系统
        ============================================
        """)
        option = input("请输入您的选择：")
        if option == "1":
            show_student_info()
        elif option == "2":
            continue
        elif option == "0":
            print("感谢使用本系统，再见！")
            exit()
        else:
            print("输入有误，请重新输入！")
 
 
 
# 展示所有学生信息
def show_all_students():
    with open('students_info.txt', 'r',encoding='utf-8') as f:
        lines = f.readlines()
        if len(lines) == 0:
            print("暂无学生信息")
            return
        header = "{:<6}{:<10}{:<10}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}{:<8}".format("姓  名", "班  级", "学  号", "年  龄", "性  别", "Linux", "Python", "C语言", "C++语言", "Java语言", "平均分")
        print(header)
        for line in lines:
            info = line.strip().split(',')
            student_info = "{:<6}{:<12}{:<12}{:<10}{:<10}{:<8}{:<8}{:<9}{:<11}{:<11}{:<8}".format(info[0], info[1], info[2], info[3], info[4], info[5], info[6], info[7], info[8], info[9], info[10])
            print(student_info)
 
 
 
# 查询单个学生的学生信息
def show_student_info():
    student_id = input("请输入要查询的学号：")
    with open('students_info.txt', 'r', encoding='utf-8') as f:
        found = False
        for line in f:
            info = line.strip().split(',')
            if info[2] == student_id:
                print(f"姓名：{info[0]}")
                print(f"班级：{info[1]}")
                print(f"学号：{info[2]}")
                print(f"年龄: {info[3]}")
                print(f"性别: {info[4]}")
                print(f"Linux成绩: {info[5]}")
                print(f"Python成绩: {info[6]}")
                print(f"C语言成绩: {info[7]}")
                print(f"C++语言成绩：{info[8]}")
                print(f"Java语言成绩: {info[9]}")
                print(f"平均分：{info[10]}")
                found = True
                break
 
        if not found:
            print("未找到该学号的学生信息")
 
 
 
# 管理员登录
def login_admin():
    while True:
        account = input("请输入账号：")
        passwd = input("请输入密码：")
        try:
            with open('admin_accounts.txt', 'r', encoding='utf-8') as f:
                for line in f:
                    info = line.strip().split(' ')
                    if len(info) != 4:
                        continue
                    # 根据文件内容里的冒号进行处理
                    name = info[0].split(':')[1]
                    num = info[1].split(':')[1]
                    acc = info[2].split(':')[1]
                    pwd = info[3].split(':')[1]
                    if (acc == account) and (pwd == passwd):
                        print(f"欢迎登陆，{name}管理员！")
                        admin_menu()
                        return
                print("账号或密码错误，请重新输入")
        except IOError:
            print("无法打开文件，请检查文件路径和权限")
            return
        except Exception as e:
            print(f"发生错误：{str(e)}")
            return
 
# 管理员菜单
def admin_menu():
    while True:
        option = input(
            "请选择操作:\n 1-重置学生账号密码\n 2-添加学生信息\n 3-删除学生信息\n 4-修改学生信息\n 5-查询学生信息\n 6-学生成绩排序\n 7-所有学生成绩\n 0-退出）：")
        if option == '1':
            reset_password()
        elif option == '2':
            add_student()
        elif option == '3':
            delete_student()
        elif option == '4':
            modify_student()
        elif option == '5':
            search_student()
        elif option == '6':
            sort_students()
        elif option == '7':
            show_all_students()
        elif option == '0':
            break
        else:
            print("输入有误，请重新输入")
 
 
# 重置学生账号密码
def reset_password():
    option = input("请选择操作(1-修改密码,2-删除账号,3-添加账号）：")
    if option == '1':
        student_id = input("请输入要修改密码的学号：")
        with open('student_accounts.txt', 'r', encoding='utf-8-sig') as f:
            lines = f.readlines()
            for i in range(len(lines)):
                line = lines[i].strip()
                info = line.split()
                if len(info) != 4:
                    continue
                name = info[0][3:]      # 姓名
                num = info[1][3:]       # 学号
                account = info[2][3:]   # 账号
                pwd = info[3][3:]       # 密码
                if num == student_id:
                    print(f"姓名：{name}，学号：{num}，账号：{account}，密码：{pwd}")
                    new_pwd = input("请输入新密码：")
                    # 修改密码
                    lines[i] = f"姓名:{name} 学号:{num} 账号:{account} 密码:{new_pwd}\n"
                    with open('student_accounts.txt', 'w', encoding='utf-8-sig') as f:
                        f.writelines(lines)
                    print("密码修改成功")
                    break
            else:
                print("未找到该学号的学生信息")
    elif option == '2':
        student_id = input("请输入要删除账号的学号：")
        with open('student_accounts.txt', 'r', encoding='utf-8-sig') as f:
            lines = f.readlines()
            for i in range(len(lines)):
                line = lines[i].strip()
                info = line.split()
                if len(info) != 4:
                    continue
                name = info[0][3:] # 姓名
                num = info[1][3:] # 学号
                account = info[2][3:] # 账号
                pwd = info[3][3:] # 密码
                if num == student_id:
                    print(f"姓名：{name}，学号：{num}，账号：{account}，密码：{pwd}")
                    # 删除账号
                    del lines[i]
                    with open('student_accounts.txt', 'w', encoding='utf-8-sig') as f:
                        f.writelines(lines)
                    print("账号删除成功")
                    break
            else:
                print("未找到该学号的学生信息")
    elif option == '3':
        new_num = input("请输入新的学号：")
        new_name = input("请输入姓名：")
        new_acc = input("请输入账号：")
        new_pwd = input("请输入密码：")
        new_line = f"姓名:{new_name} 学号:{new_num} 账号:{new_acc} 密码:{new_pwd}\n"
        with open('student_accounts.txt', 'a', encoding='utf-8-sig') as f:
            f.write(new_line)
        print("账号添加成功")
    else:
        print("输入有误，请重新选择")
 
 
 
 
# 添加学生信息
def add_student():
    student_info = input("请输入学生信息（姓名,班级,学号,年龄,性别,Linux成绩,Python成绩,C语言成绩,C++语言成绩,Java语言成绩): ")
    info_list = student_info.split(',')
    if len(info_list) < 10:
        print("输入的信息不完整，请重新输入！")
        return
    name, cls, id, age, sex, linux, python, c, cpp, java = info_list[:10]
    total_score = (int(linux) + int(python) + int(c) + int(cpp) + int(java)) / 5
    student_info = f"{name},{cls},{id},{age},{sex},{linux},{python},{c},{cpp},{java}"
    with open('students_info.txt', 'a', encoding='utf-8') as f:
        f.write(f"{student_info},{total_score}\n")
    print(f"学生信息添加成功，平均分为{total_score},平均分已自动填充")
 
 
 
# 删除学生信息
def delete_student():
    student_id = input("请输入要删除信息的学号：")
    with open('students_info.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for i in range(len(lines)):
            info = lines[i].strip().split(",")
            if info[2] == student_id:
                del lines[i]
                with open('students_info.txt', 'w', encoding='utf-8') as f:
                    f.writelines(lines)
                print("学生信息删除成功")
                break
        else:
            print("未找到该学号的学生信息")
 
 
# 修改学生信息
def modify_student():
    student_id = input("请输入要修改信息的学号：")
    with open('students_info.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        for i in range(len(lines)):
            data = lines[i].strip().split(',')
            name = data[0]
            clas = data[1]
            num = data[2]
            age = data[3]
            sex = data[4]
            Linux_score = int(data[5])
            Python_score = int(data[6])
            C_score = int(data[7])
            Cpp_score = int(data[8])
            Java_score = int(data[9])
            average_score = float(data[10])
            if num == student_id:
                new_info_str = input(
                    "请按照格式输入新的学生信息（姓名,班级,学号,年龄,性别,Linux成绩,Python成绩,C语言成绩,C++语言成绩,Java语言成绩): ")
                new_info = new_info_str.strip().split(',')
                new_name = new_info[0]
                new_class = new_info[1]
                new_num = new_info[2]
                new_age = int(new_info[3])
                new_sex = new_info[4]
                new_Linux_score = int(new_info[5])
                new_Python_score = int(new_info[6])
                new_C_score = int(new_info[7])
                new_Cpp_score = int(new_info[8])
                new_Java_score = int(new_info[9])
                new_average_score = (new_Linux_score + new_Python_score + new_C_score + new_Cpp_score + new_Java_score) / 5
                lines[i] = f"{new_name},{new_class},{new_num},{new_age},{new_sex},{new_Linux_score},{new_Python_score},{new_C_score},{new_Cpp_score},{new_Java_score},{new_average_score}\n"
                with open('students_info.txt', 'w', encoding='utf-8') as f:
                    f.writelines(lines)
                print("学生信息修改成功")
                break
        else:
            print("未找到该学号的学生信息")
 
 
 
 
# 查询学生信息
def search_student():
    student_id = input("请输入要查询信息的学号：")
    with open('students_info.txt', 'r', encoding='utf-8') as f:
        for line in f:
            data = line.strip().split(',')
            name = data[0]
            clas = data[1]
            num = data[2]
            age = data[3]
            sex = data[4]
            Linux_score = data[5]
            Python_score = data[6]
            C_score = data[7]
            Cpp_score = data[8]
            Java_score = data[9]
            average = data[10]
            if num == student_id:
                print(f"姓名: {name}")
                print(f"班级: {clas}")
                print(f"学号: {num}")
                print(f"年龄: {age}")
                print(f"性别: {sex}")
                print(f"Linux成绩: {Linux_score}")
                print(f"Python成绩: {Python_score}")
                print(f"C语言成绩: {C_score}")
                print(f"C++语言成绩：{Cpp_score}")
                print(f"Java语言成绩: {Java_score}")
                print(f"平均分：{average}")
                break
        else:
            print("未找到该学号的学生信息")
 
 
 
 
# 学生成绩排序
def sort_students():
    while True:
        option = input("请选择排序方式(1-升序, 2-降序）：")
        if option == '1':
            reverse = False
            break
        elif option == '2':
            reverse = True
            break
        else:
            print("输入有误，请重新选择")
    with open('students_info.txt', 'r', encoding='utf-8') as f:
        lines = f.readlines()
        students = []
        for line in lines:
            info = line.strip().split(',')
            score_sum = sum(map(float, info[5:]))
            students.append((info[0], info[1], info[2], *info[3:], score_sum))
        students.sort(key=lambda x: x[-1], reverse=reverse)
        print("排序结果如下：")
        print("+" + "-" * 8 + "+" + "-" * 15 + "+" + "-" * 10 + "+" + "-" * 12 +
              "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+")
        print("|{:^6}|{:^13}|{:^8}|{:^12}|{:^12}|{:^10}|{:^10}|{:^10}|{:^9}|".format(
            "姓名", "班级", "学号", "Linux", "Python", "C语言", "C++语言", "Java语言", "平均分"))
        print("+" + "-" * 8 + "+" + "-" * 15 + "+" + "-" * 10 + "+" + "-" * 12 +
              "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+")
        for student in students:
            print("|{:^6}|{:^15}|{:^10}|{:^12}|{:^12}|{:^12}|{:^12}|{:^12}|{:^12}|".format(
                student[0], student[1], student[2], student[5], student[6], student[7], student[8], student[9], student[10]))
            print("+" + "-" * 8 + "+" + "-" * 15 + "+" + "-" * 10 + "+" + "-" * 12 +
                  "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+" + "-" * 12 + "+")
 
 
if __name__ == '__main__':
    login()